import cv2
import os
import json
import shutil
import subprocess

from AlphaPose.scripts.demo_inference import pose_inference

Alphapose_path = "/home/airport/Airport_check/src/AlphaPose/"


def create_or_clear_directory(directory_path):
    # 检查目录是否存在
    if not os.path.exists(directory_path):
        # 如果目录不存在，则创建目录
        os.makedirs(directory_path)
    else:
        # 如果目录存在，则清空目录中的所有文件
        files = os.listdir(directory_path)
        for file in files:
            file_path = os.path.join(directory_path, file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f"无法删除 {file_path}: {e}")


def pose_detect(image, data_dir, current_id, frame_id, args_pose, cfg_pose, model_pose, dataset_pose, detector_pose):
    in_path = data_dir + f"bodies/{current_id}_in/"
    out_path = data_dir + f"bodies/{current_id}_out/"

    create_or_clear_directory(in_path)
    create_or_clear_directory(out_path)

    cv2.imwrite(in_path + f"pose_tmp_{frame_id}.jpg", image)

    args_pose.inputpath = in_path
    args_pose.outputpath = out_path
    pose_inference(model_pose, dataset_pose, detector_pose, args_pose, cfg_pose, in_path + f"pose_tmp_{frame_id}.jpg")

    #script_command = f"cd /home/airport/Airport_check/src/AlphaPose/ && python {Alphapose_path}scripts/demo_inference.py --cfg {Alphapose_path}configs/halpe_coco_wholebody_136/resnet/256x192_res50_lr1e-3_2x-dcn-combined.yaml --checkpoint {Alphapose_path}pretrained_models/multi_domain_fast50_dcn_combined_256x192.pth --indir {in_path} --outdir {out_path} --save_img --showbox --vis_fast"
    #ret = subprocess.run(script_command, shell=True)
    # if ret.returncode != 0:
    #     print("return error")[]
    
    with open(f"{out_path}alphapose-results.json", 'r') as openfile:
        hm_object = json.load(openfile)

    return hm_object

